package com.mycase.im.boot.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mycase.im.boot.entity.database.ImUser;
import com.mycase.im.boot.exception.CustomException;
import com.mycase.im.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.properties.Callable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;

/**
 * @Author ZhuHJay
 * @Date 2021/8/5 19:43
 */
@Component("UserDetailsService")
@Slf4j
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        log.warn("自定义用户细节服务 loadUserByUsername() -> {}", username);
        UserDetails userDetails = null;

        ImUser user = userService.getOne(new QueryWrapper<ImUser>().eq("account", username));

        if( !ObjectUtils.isEmpty(user) ){
            userDetails = new User(user.getAccount(),
                    user.getPassword(),
                    // 该账号是否可用
                    user.getStatus() == 1,
                    true,
                    true,
                    true,
                    Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
        }

        return userDetails;
    }

}
